package logic

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"strconv"
	"time"
	"user_srv/models/mysql"
	"user_srv/pkg"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderCreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderCreateLogic {
	return &OrderCreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderCreateLogic) OrderCreate(in *user.OrderCreateRequest) (*user.OrderCreateResponse, error) {
	// todo: add your logic here and delete this line
	var house mysql.House
	err := house.HouseView(in.HouseId)
	if err != nil {
		logx.Info("房源信息不存在", err)
		return nil, errors.New("房源信息不存在")
	}
	if house.HouseStatus != 2 {
		logx.Info("房源信息审核中", err)
		return nil, errors.New("房源信息审核中")
	}
	orderSn := uuid.NewString()
	payTime := time.Now().Format(time.DateTime)
	order := mysql.Order{
		UserId:  in.UserId,
		OrderSn: orderSn,
		PayType: 1,
		PayTime: payTime,
		Amount:  house.Price,
	}
	err = order.Create()
	if err != nil {
		logx.Info("创建订单信息失败")
		return nil, errors.New("创建订单信息失败")
	}
	totalAmount := strconv.FormatInt(house.Price, 10)
	aLiPay := pkg.ALiPay{
		Subject:     "房源支付",
		OutTradeNo:  orderSn,
		TotalAmount: totalAmount,
	}
	UrlPay := aLiPay.Pay()
	return &user.OrderCreateResponse{
		OrderId: int64(order.ID),
		UrlPay:  UrlPay,
	}, nil
}
